<template>
  <div style="display: flex">
    <div :class="[isShow ? 'sidebar' : 'sidebar noWidth']">
      <div class="wrap_category" v-show="showSiderContent">
        <div>
          <el-tree :data="categoryList" :props="defaultProps" @node-click="handleNodeClick" :highlight-current="true"
            :render-content="renderContent">
          </el-tree>
        </div>
        <div style='padding: 56px 12px'>
          <el-button plain @click="showDialog('create')">+ 添加</el-button>
          <el-button plain @click="showDialog('update')">编辑</el-button>
          <el-button plain style='margin-left: 0; margin-top: 16px' @click="showRemove">- 删除</el-button>
        </div>
        <el-dialog :title="btnType === 'create' ?  '添加分类' : '编辑分类'"
          :visible.sync="dialogVisible" center width="30%" :show-close="false" :close-on-click-modal="false">
          <div style="text-align: center">
            <el-input v-model="categoryName" placeholder="请输入分类名称(20字以内)" maxlength="20"></el-input>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button plain @click="onCancelDialog">取消</el-button>
            <el-button type="primary" @click="updateCategory">确 定</el-button>
          </div>
        </el-dialog>
        <el-dialog title="是否删除此分类"
          :visible.sync="dialogRemoveVisible" center width="30%" :show-close="false" :close-on-click-modal="false">
          <div style="text-align: center">
            <el-button plain @click="onCancelDialog">取消</el-button>
            <el-button type="primary" @click="removeCategory">确 定</el-button>
          </div>
        </el-dialog>
      </div>
      <a :class="[isShow ? 'leftBtn el-icon-d-arrow-left' : 'rightBtn el-icon-d-arrow-right' , 'btn']" @click="showBar"></a>
    </div>
    <div style="width: 100%; overflow-x: scroll">
      <el-table
        v-loading="loading"
        element-loading-text="正在加载..."
        ref="multipleTable"
        @selection-change="handleSelectionChange"
        :data="tableData" border style="width: 100%;text-align: center">
        <el-table-column
          type="selection"
          width="35">
        </el-table-column>
        <el-table-column fixed="left"
          prop="item.itemNum"
          label="物资编码,Item Code"
          min-width="120px" :render-header="renderHeader">
        </el-table-column>
        <el-table-column
          prop="item.itemDesc"
          label="物资描述,Item Description"
          min-width="260px" :render-header="renderHeader">
        </el-table-column>
        <el-table-column
          prop="item.minimumOrderQuantity"
          label="最小订货量,MOQ"
          min-width="120px" :render-header="renderHeader">
        </el-table-column>
        <el-table-column
          prop="item.quantity"
          label="数量,Quantity"
          min-width="150" :render-header="renderHeader">
        </el-table-column>
        <el-table-column fixed="right"
          prop=""
          label="操作,Operation"
          min-width="100"
          :render-header="renderHeader">
          <template slot-scope="scope">
            <div style="text-align: center">
                <el-tooltip content="Add To The Application" placement="top">
                    <el-button @click="onBatch(scope.row,'single')" type="text"
                               size="small" class="el-icon-materials-gouwuchetianjia"></el-button>
                </el-tooltip>
                <el-tooltip content="Delete" placement="top">
                    <el-button @click="onRemove(scope.row, 'single')" type="text"
                               size="small" class="el-icon-delete" style="font-size: 24px"></el-button>
                </el-tooltip>


            </div>
          </template>
        </el-table-column>
      </el-table>
      <v-pagination :page-data="pageData" @onPageChange="onPageChange" v-if="!isEmpty"></v-pagination>
      <div style='width: 100%; padding: 36px 0; text-align: right'>
          <el-tooltip content="Classification Of export" placement="top">
              <el-button type="success" round @click="onExport">分类导出</el-button>
          </el-tooltip>
          <el-tooltip content="Add To The Application Form" placement="top">
              <el-button type="success" round @click="onBatch">加入申请单</el-button>
          </el-tooltip>
          <el-tooltip content="Delete" placement="top">
              <el-popover
                  placement="top"
                  width="160"
                  v-model="popoverVisible">
                  <p>是否批量删除常用物料？</p>
                  <div style="text-align: right; margin: 16px 0 0 0">
                      <el-button size="mini" type="primary" @click="popoverVisible = false">再想想</el-button>
                      <el-button type="success" size="mini" @click="onRemove">删除</el-button>
                  </div>
                  <el-button type="primary" round slot="reference" style="margin-right: 36px">删除</el-button>
              </el-popover>
          </el-tooltip>


      </div>
    </div>
  </div>
</template>

<script>
  import { queryMaterials, categoryList, addCategory, updateCategory, removeCategory, addMaterial, batchApplication,
    removeMaterials, batchDeleteMaterial } from "../../../components/axios/url";
  import http from "../../../components/axios/fetch";
  import SERVER from "../../../components/axios/config";
  import bus from "../../common/bus";
  import vPagination from '../../common/Pagination.vue';
  import renderHeader from '../../common/renderHeader.js';
  import {UserHelper} from "../../helpers/UserHelper";
  import { ObjectUtil } from "../../../components/axios/objectUtils";
  export default {
    name: "material-list",
    components:{
      vPagination
    },
    props: ['applyId'],
    data() {
      return {
        isShow: true,
        showSiderContent: true,
        isEmpty: true,
        dialogVisible: false,
        dialogRemoveVisible: false,
        categoryList: [],
        categoryName: '',
        btnType: null,
        parentId: null,
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        pageData: {},
        page: 1,
        tableData: [],
        multipleSelection: [],
        loading: false,
        popoverVisible: false
      }
    },
    mounted() {
      bus.$on("tabType", (name)=>{
        if(name === 'material') {
          this.resetAll();
          this.getCategoryList();
        }
      });
    },
    methods: {
      renderHeader: renderHeader,
      showBar() { //显示隐藏bar
        setTimeout(() => {
          this.showSiderContent = !this.showSiderContent;
        },60)
        this.isShow = !this.isShow;
      },
      renderContent(h, { node, data, store }) {
        return (
        <div style="font-size: 14px; overflow: hidden; text-overflow:ellipsis; white-space: nowrap; border-radius: 3px">
          <span style={data.id === this.parentId? 'background: #B4E5FD; padding: 3px 8px' : ''}
            title={node.label}>{node.label}</span>
        </div>);
      },
      onCancelDialog() { //关闭弹框
        this.resetCategory();
      },
      showDialog(type) { //显示新增编辑弹框
        if(type === 'update' && !this.parentId) {
          this.$notify.warning({
            title: '提示',
            message: '请选择要修改的分类',
          });
          return;
        }
        if(type === 'create') {
          this.categoryName = '';
        }
        this.dialogVisible = true;
        this.btnType = type;
      },
      showRemove() { //显示删除弹框
        if(!this.parentId) {
          this.$notify.warning({
            title: '提示',
            message: '请选择要删除的分类',
          });
          return;
        }
        this.dialogRemoveVisible = true;
      },
      updateCategory() { //新增编辑提交事件
        let postUrl, param;
        if(this.btnType === 'create') {
          postUrl = addCategory;
          param = {
            userId: UserHelper.getUserId(),
            name: this.categoryName,
            parentId: this.parentId
          }
        }
        if(this.btnType === 'update') {
          postUrl = updateCategory;
          param = {
            name: this.categoryName,
            id: this.parentId
          }
        }
        this.resetCategory();
        http.post(postUrl, param).then(res => {
          if(res.data && res.data.resultMess === "success") {
            this.getCategoryList();
          } else {
            this.$notify.error({
              title: '提示',
              message: res.data.resultMess,
            });
          }
        }).catch((error) => {
          this.loading = false;
          this.$notify.error({
            title: '提示',
            message: '网络错误',
          });
        })
      },
      removeCategory() { //删除分类
        http.post(removeCategory, {categoryId: this.parentId}).then(res => {
          if(res.data && res.data.resultMess === "success") {
            this.getCategoryList();
          } else {
            this.$notify.error({
              title: '提示',
              message: res.data.resultMess,
            });
          }
        }).catch((error) => {
          this.loading = false;
          this.$notify.error({
            title: '提示',
            message: '网络错误',
          });
        })
        this.resetCategory();
      },
      getCategoryList() { //获取所有分类
        http.post(categoryList,{userId: UserHelper.getUserId()}).then(res => {
          if(res.data && res.data.data && res.data.resultMess === "success") {
            this.categoryList = ObjectUtil.getTreeData(res.data.data.list);
          } else {
            this.$notify.error({
              title: '提示',
              message: res.data.resultMess,
            });
          }
        }).catch((error) => {
          this.$notify.error({
            title: '提示',
            message: '网络错误',
          });
        })
      },
      handleNodeClick(data) { //点击分类节点事件
        if(this.parentId === data.id) {
          this.parentId = null;
          this.categoryName = '';
          this.pageData = {};
          this.page = 1;
          this.tableData = [];
          this.multipleSelection = [];
          return;
        }
        this.parentId = data.id;
        this.categoryName = data.name;
        this.getMaterialList({categoryId: data.id});
      },
      resetCategory() { //重置数据
        this.dialogVisible = false;
        this.dialogRemoveVisible = false;
        this.parentId = null;
        this.btnType = '';
        this.categoryName = '';
      },
      getMaterialList(param) {
        //获取常用材料列表
        this.loading = true;
        http.post(queryMaterials, param).then(res => {
          if(res.data && res.data.resultMess === "success") {
            this.tableData = res.data.data.list;
            this.pageData = res.data.data.page;
            this.isEmpty = res.data.data.list.length === 0;
          } else {
            this.$notify.error({
              title: '提示',
              message: res.data.resultMess,
            });
          }
          this.loading = false;
        }).catch((error) => {
          this.loading = false;
          this.$notify.error({
            title: '提示',
            message: '网络错误',
          });
        })
      },
      onPageChange(page) {
        //翻页事件
        this.page = page;
        this.multipleSelection = [];
        const param = {
          page: page,
          categoryId: this.parentId
        }
        this.getMaterialList(param);
      },
      handleSelectionChange(val) { //勾选事件
        this.multipleSelection = val;
      },
      getInfoNo: function() {
        //获取申请单数量信息
      },
      onBatch: function(row, type) { //加入申请单
        if(type !== 'single' && !this.multipleSelection.length > 0) {
          this.$notify({
            title: '提示',
            message: '请先勾选物资',
            type: 'warning'
          });
          return;
        }
        //批量加入申请单
        let postUrl, param;
        if(type === 'single') {
          postUrl = addMaterial;
          param = {applyId: this.applyId, inventoryItemId: row.inventoryItemId, quantity: row.item && row.item.quantity || null}
        } else {
          const materialList = this.multipleSelection.map((data) => ({inventoryItemId: data.inventoryItemId, quantity: data.item && data.item.quantity || null}));
          param = {applyId: this.applyId, materialListJson: JSON.stringify(materialList)};
          postUrl = batchApplication;
          this.multipleSelection = [];
        }

        http.post(postUrl, param).then(res => {
          let type, content;
          if(res.data.resultMess === "success") {
            type = 'success';
            content = {title: '提示', message: `加入申请单成功`}
            this.getMaterialTotal();
          } else {
            type = 'error';
            content = {title: '提示', message: res.data.resultMess}
          }
          this.$notify[type](content);
          this.getMaterialList({page: this.page, categoryId: this.parentId});
        }).catch((error) => {
          this.$notify.error({
            title: '提示',
            message: '网络错误',
          });
        })
      },
      onRemove: function(row, type) {
        this.popoverVisible = false;
        if(type !== 'single' && !this.multipleSelection.length > 0) {
          this.$notify({
            title: '提示',
            message: '请先勾选物资',
            type: 'warning'
          });
          return;
        }
        //批量加入申请单
        let postUrl, param;
        if(type === 'single') {
          postUrl = removeMaterials;
          param = {categoryMaterialId: row.id}
        } else {
          const materialList = this.multipleSelection.map((item) => item.id);
          param = {categoryMaterialIds: materialList.join(',')};
          postUrl = batchDeleteMaterial;
          this.multipleSelection = [];
        }

        http.post(postUrl, param).then(res => {
          let type, content;
          if(res.data && res.data.resultMess === "success") {
            type = 'success';
            content = {title: '提示', message: "删除成功"}
          } else {
            type = 'error';
            content = {title: '提示', message: res.data.resultMess}
          }
          this.$notify[type](content);
          this.getMaterialList({page: this.page, categoryId: this.parentId});
        }).catch((error) => {
          this.$notify.error({
            title: '提示',
            message: '网络错误',
          });
        })
      },
      onExport: function() {
        if(!this.parentId) {
          this.$notify({
            title: '提示',
            message: '请选择需要导出的分类',
            type: 'warning'
          });
          return;
        }
        console.log(SERVER,'SERVER')
        window.location = `${SERVER.host}category/export?categoryId=${this.parentId}&_st=${UserHelper.getToken()}`
      },
      getMaterialTotal: async function() { //获取加入申请单数量
        this.$emit('getMaterialTotal', null)
      },
      resetAll() { //重置所有数据
        this.isShow = true;
        this.showSiderContent = true;
        this.isEmpty = true;
        this.dialogVisible = false;
        this.dialogRemoveVisible = false;
        this.categoryList = [];
        this.categoryName = "";
        this.parentId = null;
        this.btnType = '';
        this.pageData = {};
        this.page = 1;
        this.tableData = [];
        this.multipleSelection = [];
        this.loading =  false;
      }
    }
  }
</script>

<style scoped>
  .sidebar{
    position: relative;
    width: 220px;
    min-height: 420px;
    border-right: 1px solid #ccc;
    margin-right: 12px;
    transition: all .3s;
    -moz-transition: all .3s; /* Firefox 4 */
    -webkit-transition: all .3s; /* Safari 和 Chrome */
  }
  .noWidth{
    width: 0px;
    border-color: transparent;
  }
  .btn{
    position: absolute;
    width: 24px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    top: 50%;
    font-size: 24px;
    background: #c4c4c4;
    color: #fff;
    cursor: pointer;
    transform: translate(0, -50%);
    -webkit-transform: translate(0, -50%);
    z-index: 9;
    transition: all .3s;
    -moz-transition: all .3s; /* Firefox 4 */
    -webkit-transition: all .3s; /* Safari 和 Chrome */
  }
  .leftBtn{
    left: 196px;
    border-radius: 23% 0 0 23%;
  }
  .rightBtn{
    left: 0;
    border-radius: 0 23% 23% 0;
  }
  .wrap_category{
    width: 220px;
    padding: 16px 16px 16px 0;
  }
</style>
